<template>
  <div :id="id" class="lg-echarts"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, watch } from 'vue';
import { deepCopy, deepMerge, nextId } from '@/soar';

type EChartsOption = echarts.EChartsOption;
type ECharts = echarts.EChartsType;

interface Props {
  option: EChartsOption;
}
const props = defineProps<Props>();

const id = `e${nextId()}`;
let container: ECharts;
let innerOption: EChartsOption;

function setOption(option: EChartsOption) {
  innerOption = deepCopy(option || {}, true);
  if (container) {
    container.setOption(innerOption);
  }
}

function updateOption(option: EChartsOption) {
  deepMerge(innerOption, option);
  setOption(innerOption);
}

onMounted(() => {
  container = echarts.init(document.getElementById(id));
  setOption(props.option);
});

watch(() => props.option, setOption, { deep: true });

defineExpose({
  setOption,
  updateOption,
});
</script>
<script lang="ts">
export default {
  name: 'LgEcharts',
};
</script>
